package cc.linker.steplink.crm.controller;


import cc.linker.steplink.crm.commons.http.HttpService;
import cc.linker.steplink.crm.commons.model.PcUserInfo;
import cc.linker.steplink.crm.merchanth5.commons.UserInfoUtil;
import cc.linker.steplink.crm.merchant.dao.NewMallDao;
import cc.linker.steplink.crm.response.GlobalException;
import cc.linker.steplink.crm.response.ResponseCode;
import cc.linker.steplink.crm.service.ITemplateMessageService;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.mongodb.util.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.net.URISyntaxException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/tempmsg")
public class TemplateMessageController {

    @Value("${system.scrm.wxpushurl}")
    private String url;

    @Autowired
    private ITemplateMessageService tempMsgService;

    @Autowired
    private HttpService httpService;

    @Autowired
    private NewMallDao newMallDao;
    @Autowired
    private UserInfoUtil userInfoUtil;

    /**
     * 获取模板消息列表
     * @param pn
     * @param pageSize
     * @param session
     * @return
     * @throws Exception
     */

    @GetMapping("/list")
    public Object list(@RequestParam(value = "pn", defaultValue = "1", required = false) Integer pn,
                            @RequestParam(value = "pageSize", defaultValue = "20", required = false) Integer pageSize,
                       HttpServletRequest request) throws Exception {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        PageHelper.startPage(pn, pageSize);
        String orgId = userinfo.getOrgId();
        if (StringUtils.isEmpty(orgId)) {
            throw new GlobalException(ResponseCode.INFO_OBTAIN_FAIL);
        }
        List<Map<String, Object>> list = tempMsgService.list(orgId);
        if(null == list || list.size()<4){
            return new PageInfo<>(this.baselist(orgId));
        }
        return new PageInfo<>(list);
    }


    /**
     * 写入基础数据
     * @param orgId
     * @return
     * @throws Exception
     */
    public List<Map> baselist(String orgId) throws Exception {
        Map<String, String> baseLevel = new HashMap<String, String>();
        baseLevel.put("orgId", orgId);
        baseLevel.put("tempMsgId", UUID.randomUUID().toString());
        baseLevel.put("title", "会员等级变更通知");
        baseLevel.put("keyWord", "会员等级、新会员等级、新会员权益、新会员礼包");
        baseLevel.put("templateType", "2");
        baseLevel.put("status", "0");
        tempMsgService.add(baseLevel);

        Map<String, String> baseScore = new HashMap<String, String>();
        baseScore.put("orgId", orgId);
        baseScore.put("tempMsgId", UUID.randomUUID().toString());
        baseScore.put("title", "会员积分变动通知");
        baseScore.put("keyWord", "会员等级、积分、变动");
        baseScore.put("templateType", "1");
        baseScore.put("status", "0");
        tempMsgService.add(baseScore);

        Map<String, String> baseBuy = new HashMap<String, String>();
        baseBuy.put("orgId", orgId);
        baseBuy.put("tempMsgId", UUID.randomUUID().toString());
        baseBuy.put("title", "购买成功通知");
        baseBuy.put("keyWord", "订单商品、订单编号、订单金额、支付时间");
        baseBuy.put("templateType", "3");
        baseBuy.put("status", "0");
        tempMsgService.add(baseBuy);

        Map<String, String> baseSend = new HashMap<String, String>();
        baseSend.put("orgId", orgId);
        baseSend.put("tempMsgId", UUID.randomUUID().toString());
        baseSend.put("title", "订单发货通知");
        baseSend.put("keyWord", "订单编号、发货时间、物流公司、快递单号、收件信息");
        baseSend.put("templateType", "4");
        baseSend.put("status", "0");
        tempMsgService.add(baseSend);



        List<Map> result = new ArrayList<>();
        result.add(baseLevel);
        result.add(baseScore);
        result.add(baseBuy);
        result.add(baseSend);
        return result;
    }

    @GetMapping("/getinfo")
    public Object info(@RequestParam(value = "tempMsgId", required = true) String tempMsgId, HttpServletRequest request) throws Exception {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        String orgId = userinfo.getOrgId();
        if (StringUtils.isEmpty(orgId)) {
            throw new GlobalException(ResponseCode.INFO_OBTAIN_FAIL);
        }
        HashMap<String, Object> info = tempMsgService.getInfo(tempMsgId);
        return info;
    }

    @PostMapping("edit")
    public void edit(@RequestBody Map<String, Object> map, HttpServletRequest request) throws Exception {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        String orgId = userinfo.getOrgId();
        if (StringUtils.isEmpty(orgId)) {
            throw new GlobalException(ResponseCode.INFO_OBTAIN_FAIL);
        }
        if (null == map.get("tempMsgId") || "".equals(map.get("tempMsgId"))) {
            throw new GlobalException(ResponseCode.ID_NULL);
        }

        String status = map.get("status").toString();
        HashMap<String, Object> tempMsgInfo = tempMsgService.getInfo(map.get("tempMsgId").toString());
        if ("0".equals(tempMsgInfo.get("status").toString()) && "1".equals(status)) {
            SimpleDateFormat utime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            map.put("lastOpenTime", utime.format(new Date()));
        }
        tempMsgService.edit(map);
    }

    /**
     * 启用/禁用模板消息
     * @param session
     * @param map
     * @return
     * @throws Exception
     */
    @PostMapping("/changestatus")
    public boolean changeStatus(HttpServletRequest request,@RequestBody Map<String, String> map) throws Exception {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        String orgId = userinfo.getOrgId();
        if(StringUtils.isEmpty(map.get("tempMsgId"))){
            throw GlobalException.build("参数错误");
        }
        HashMap<String, Object> info = tempMsgService.getInfo(map.get("tempMsgId"));
        if(null == info){
            throw GlobalException.build("非法操作");
        }
        Map<String, Object> data = new HashMap<>();
        if("1".equals(info.get("status").toString())){
            data.put("tempMsgId",map.get("tempMsgId"));
            data.put("status","0");
            return tempMsgService.edit(data);
        }else{
            if(null==info.get("templateId") || StringUtils.isEmpty(info.get("templateId"))){
                data.put("tempMsgId",map.get("tempMsgId"));
                data.put("status","1");

                new Thread(()->{
                    try {
                        Thread.sleep(40*1000L);
                        String token = newMallDao.getTokenByOrgId(orgId);
                        boolean b = this.checkIndustry(token);
                        if(!b){
                            this.setIndustry(token);
                        }
                        String templateId = this.getTemplateId(token, info.get("templateType").toString());
                        Map<String, Object> thrData = new HashMap<>();
                        thrData.put("tempMsgId",map.get("tempMsgId"));
                        thrData.put("templateId",templateId);
                        SimpleDateFormat utime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        thrData.put("lastOpenTime",utime.format(new Date()));
                        tempMsgService.edit(thrData);
                    }catch (Exception e){
                        LOGGER.error("changestatus捕获错误：",e);
                    }
                }).start();

                return tempMsgService.edit(data);
            }else{
                data.put("tempMsgId",map.get("tempMsgId"));
                data.put("status","1");
                return tempMsgService.edit(data);
            }

        }
    }


    /**
     * 检查该机构绑定的公众号所属行业
     * @param token
     * @return
     */
    protected boolean checkIndustry(String token) throws IOException, URISyntaxException {
        Map<String, String> pushdata = new HashMap<>();
        pushdata.put("action", "getIndustry");
        pushdata.put("token", token);
        Map<String, String> postParam = new HashMap<>();
        postParam.put("Content-Type", "application/json;charset=UTF-8");
        JSONObject jsonObject = (JSONObject) JSONArray.toJSON(pushdata);
        Object postresJson = httpService.doPost(url,jsonObject.toJSONString(),postParam);
        Map postres  = (Map) JSON.parse(postresJson.toString());
        if("200".equals(postres.get("errcode").toString())){
            String industry  = postres.get("data").toString();
            return industry.contains("IT科技") && industry.contains("互联网|电子商务");
        }else{
            throw GlobalException.build(postres.get("msg").toString());
        }
    }

    /**
     * 设置该机构绑定的公众号所属行业
     * @param token
     * @return
     */
    protected void setIndustry(String token) throws IOException, URISyntaxException {
        Map<String, Object> pushdata = new HashMap<>();
        pushdata.put("action", "setIndustry");
        pushdata.put("token", token);
        pushdata.put("industry_id1", 1);
        pushdata.put("industry_id2", 37);
        Map<String, String> postParam = new HashMap<>();
        postParam.put("Content-Type", "application/json;charset=UTF-8");
        JSONObject jsonObject = (JSONObject) JSONArray.toJSON(pushdata);
        Object postresJson = httpService.doPost(url,jsonObject.toJSONString(),postParam);
        Map postres  = (Map) JSON.parse(postresJson.toString());
        if(!"200".equals(postres.get("errcode").toString())){
            throw GlobalException.build(postres.get("msg").toString());
        }
    }

    protected String getTemplateId(String token,String msgType) throws IOException, URISyntaxException {
        String templateId = "";
        Map<String, Object> getTokenTemplateList = new HashMap<>();
        getTokenTemplateList.put("action", "getAllPrivateTemplate");
        getTokenTemplateList.put("token", token);
        Map<String, String> getTokenTemplatePostParam = new HashMap<>();
        getTokenTemplatePostParam.put("Content-Type", "application/json;charset=UTF-8");
        JSONObject getTokenTemplateObject = (JSONObject) JSONArray.toJSON(getTokenTemplateList);
        Object getTokenTemplateJson = httpService.doPost(url,getTokenTemplateObject.toJSONString(),getTokenTemplatePostParam);
        Map tokenTemplate  = (Map) JSON.parse(getTokenTemplateJson.toString());
        if("200".equals(tokenTemplate.get("errcode").toString())){
            Map data = (Map)JSON.parse(tokenTemplate.get("data").toString());
            List<Map<String,Object>> templateList = (List)data.get("template_list");
            //购买成功通知
            if("3".equals(msgType)){
                for(Map<String,Object> template : templateList){
                    if("购买成功通知".equals(template.get("title"))){
                        templateId = template.get("template_id").toString();
                    }
                }
            }
            //订单发货通知
            if("4".equals(msgType)){
                for(Map<String,Object> template : templateList){
                    if("订单发货通知".equals(template.get("title"))){
                        templateId = template.get("template_id").toString();
                    }
                }
            }
        }
        if(StringUtils.isEmpty(templateId)){
            Map<String, Object> pushdata = new HashMap<>();
            pushdata.put("action", "addTemplate");
            pushdata.put("token", token);
            //购买成功通知
            if("3".equals(msgType)){
                pushdata.put("templateIdShort", "OPENTM410086703");
            }
            //订单发货通知
            if("4".equals(msgType)){
                pushdata.put("templateIdShort", "OPENTM414956350");
            }
            Map<String, String> postParam = new HashMap<>();
            postParam.put("Content-Type", "application/json;charset=UTF-8");
            JSONObject jsonObject = (JSONObject) JSONArray.toJSON(pushdata);
            Object postresJson = httpService.doPost(url,jsonObject.toJSONString(),postParam);
            Map postres  = (Map) JSON.parse(postresJson.toString());
            if("0".equals(postres.get("errcode").toString())){
                templateId = postres.get("data").toString();
            }else{
                LOGGER.error("获取模板Id捕获错误：" + postres.toString());
                throw GlobalException.build(postres.get("msg").toString());
            }
        }
        return templateId;
    }


    /**
     *
     * orgId-机构id,orderSn-订单号,sendTime-订单发货的时间,expressCompany-物流公司：发货时填写，没有则展示“不需要物流”,
     * expressSn-快递单号：发货时填写，没有则展示“不需要物流”,receiveInfo-收件信息：收货人+手机号+收货地址（王先生 135xxxxxxxx 广东省深圳市龙华区建设东路）
     * url-订单列表页面,openid-购买人的openid
     * @throws IOException
     * @throws URISyntaxException
     */
    @PostMapping("/test")
    public void test(@RequestBody Map<String, String> rule) throws IOException, URISyntaxException {
        Map<String, String> postParam = new HashMap<>();
        postParam.put("orgId",rule.get("orgId"));
        postParam.put("orderSn",rule.get("orderSn"));
        postParam.put("sendTime",rule.get("sendTime"));
        postParam.put("expressCompany",rule.get("expressCompany"));
        postParam.put("expressSn",rule.get("expressSn"));
        postParam.put("receiveInfo",rule.get("receiveInfo"));
        postParam.put("url",rule.get("url"));
        postParam.put("openid",rule.get("openid"));
        tempMsgService.sendDeliveryMsg(postParam);
    }

}
